package cn.edu.scau.sec.caixiaoqing.client;

import cn.edu.scau.sec.caixiaoqing.spring.beans.Student;
import cn.edu.scau.sec.caixiaoqing.spring.beans.Teacher;
import cn.edu.scau.sec.caixiaoqing.spring.utils.BeanSingletonUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringBeanTest {

    public static void main(String[] args) {

        //普通测试
        testApplicationContest();

        //单例测试
        testSingletonApplicationContest();
    }

    private static void testApplicationContest(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

        Student student = (Student) applicationContext.getBean("student");

        Teacher tutor = (Teacher) applicationContext.getBean("tutor");

        System.out.println("学生的对象是：" + student + "\n" + "老师的对象是：" + tutor);

        System.out.println(student.getName() + "的体系结构课程的老师是：" + tutor.getName());

        ApplicationContext applicationContext2 = new ClassPathXmlApplicationContext("applicationContext.xml");

        Student student2 = (Student) applicationContext2.getBean("student");

        Teacher tutor2 = (Teacher) applicationContext2.getBean("tutor");

        System.out.println("学生的对象是：" + student2 + "\n" + "老师的对象是：" + tutor2);

        System.out.println(student2.getName() + "的体系结构课程的老师是：" + tutor2.getName());

        System.out.println( student == student2 ? "两次的学生对象是同一个。" : "两次的学生对象不是同一个");
        System.out.println( tutor == tutor2 ? "两次的老师对象是同一个。" : "两次的老师对象不是同一个");
    }

    private static void testSingletonApplicationContest(){

        ApplicationContext applicationContext = BeanSingletonUtils.getInstance();

        Student student = (Student) applicationContext.getBean("student");

        Teacher tutor = (Teacher) applicationContext.getBean("tutor");

        System.out.println("学生的对象是：" + student + "\n" + "老师的对象是：" + tutor);

        System.out.println(student.getName() + "的体系结构课程的老师是：" + tutor.getName());

        ApplicationContext applicationContext2 = BeanSingletonUtils.getInstance();

        Student student2 = (Student) applicationContext2.getBean("student");

        Teacher tutor2 = (Teacher) applicationContext2.getBean("tutor");

        System.out.println("学生的对象是：" + student2 + "\n" + "老师的对象是：" + tutor2);

        System.out.println(student2.getName() + "的体系结构课程的老师是：" + tutor2.getName());

        System.out.println( student == student2 ? "两次的学生对象是同一个。" : "两次的学生对象不是同一个");
        System.out.println( tutor == tutor2 ? "两次的老师对象是同一个。" : "两次的老师对象不是同一个");
    }
}
